import { makeAutoObservable, toJS } from 'mobx';
import Taro from '@tarojs/taro';
import { getItemForPk, IProduct } from '@/config/product';
import { getWechatTicket } from '@/services/aepDeviceApi';
import { getWxModeId } from '@/services/messages';

import { getWxDeviceSN } from '@/utils';
import moment from 'moment';
import gizwitsSdk from './gizwitsSdk';

class DeviceDetail {
  device: IDevice | undefined = undefined;

  deviceData: IDeviceData | undefined = undefined;

  deviceTimeCorrectModalShow: boolean = false;

  productConfig: IProduct | undefined = undefined;

  faqDetail: IFAQ | undefined = undefined;
  dontUpdateKey: string[] = [];
  lastSendCmdTimestamp: number = moment().valueOf();
  chunkCache: Record<string, any> = {};
  debounceTimer: ReturnType<typeof setTimeout> | null = null;

  customInfoMap: any; // RN的模板是模板有自己的model来存储信息；微信模板并没有这一设计，这个字段作为模板自己存放数据使用

  constructor() {
    makeAutoObservable(this);
  }

  updateDeviceDetail(device: IDevice) {
    if (device) {
      if (!this.device || this.device.productKey !== device.productKey) {
        this.productConfig = getItemForPk(device.productKey);
      }
    } else {
      this.productConfig = undefined;
    }
    this.device = device;
  }

  updateDeviceData(deviceData: IDeviceData) {
    const newDeviceData = toJS(deviceData);
    const currentTimestamp = moment().valueOf();
    const interval = currentTimestamp - this.lastSendCmdTimestamp;
    if (newDeviceData.data && this.deviceData?.data && this.lastSendCmdTimestamp && interval < 2000) {
      // 在1s内，不更新刚刚下发的数据点
      this.dontUpdateKey.forEach(key => {
        newDeviceData.data[key] = this.deviceData?.data[key];
      });
    }
    this.deviceData = newDeviceData;
  }

  async sendCmd(data: { [key: string]: any }) {
    // setTimeout(() => App.callService('sendCmd', data), 100);
    if (this.device) {
      gizwitsSdk.sendCmd({ device: this.device, data });
      this.lastSendCmdTimestamp = moment().valueOf();
      this.deviceData = { ...this.deviceData, data: { ...this.deviceData?.data, ...data } };
      this.dontUpdateKey = Object.keys(data);
    }
  }

  async sendBroadCastBigData(data: number[]) {
    if (this.device) {
      return await gizwitsSdk.sendBroadCastBigData({ device: this.device, data });
    }
    return new Promise(resolve => resolve({ success: false }));
  }

  async sendCmdChunk(data: { [key: string]: any }, timeout: number) {
    this.deviceData = { ...this.deviceData, data: { ...this.deviceData?.data, ...data } };
    // 将每次传入的数据合并到chunkCache中
    for (let key in data) {
      this.chunkCache[key] = data[key];
    }

    // 如果已经有一个计时器在等待，那么我们就不创建新的计时器，直接返回
    if (this.debounceTimer) return;

    // 设置一个计时器，当timeout时间过去后，调用sendCmd函数发送数据，并清空chunkCache
    this.debounceTimer = setTimeout(() => {
      this.sendCmd(toJS(this.chunkCache));
      this.chunkCache = {};
      this.debounceTimer = null;
    }, timeout);
  }

  virtualDeviceSendCmd(data: any) {
    this.deviceData = {
      ...this.deviceData,
      data: {
        ...this.deviceData?.data,
        ...data,
      },
      fromCmd: true,
      sourceData: { ...data },
    };
  }

  virtualRenameDevice(name: string) {
    this.device = {
      ...this.device,
      name,
    };
  }

  setDeviceTimeCorrectModal = (show: boolean) => {
    this.deviceTimeCorrectModalShow = show;
  };

  updateCustomInfoMap = (infoMap: any) => {
    this.customInfoMap = infoMap;
  };

  // 退出页面的话，需要删除掉设备
  cleanData() {
    console.log('deviceDetail cleanData');
    this.device = undefined;
    this.deviceData = undefined;
    this.deviceTimeCorrectModalShow = false;
    this.productConfig = undefined;
    this.customInfoMap = undefined;
  }

  setFAQDetail(faq: IFAQ) {
    this.faqDetail = faq;
  }
}

const DeviceDetail_Store_Key = 'deviceDetail';
export { DeviceDetail, DeviceDetail_Store_Key };

export default new DeviceDetail();
